from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404
from django.views.generic.list_detail import object_list, object_detail
from django.http import HttpResponseRedirect, Http404

from lib.decorators import render_to
from lib.shortcuts import int_or_404

def history_list(request, content_type, object_id, **kwargs):
    ctype = get_object_or_404(ContentType, model=content_type)
    main_obj = get_object_or_404(ctype.model_class(), pk=object_id)
    if 'num1' in request.GET and 'num2' in request.GET:
        return history_compare(request, main_obj)
    queryset = main_obj.history.all().order_by('-hst_revision')
    kwargs['queryset'] = queryset
    kwargs['extra_context'] = {'main_obj': main_obj}
    kwargs['template_name'] = 'history/history_list.html'
    return object_list(request, **kwargs)

@render_to('history/history_compare.html')
def history_compare(request, main_obj):
    num1, num2 = request.GET['num1'], request.GET['num2']
    num1 = int_or_404(num1)
    num2 = int_or_404(num2)
    if num1 > num2:
        num1, num2 = num2, num1
    rev1 = get_object_or_404(main_obj.history, hst_revision=num1)
    rev2 = get_object_or_404(main_obj.history, hst_revision=num2)
    return {'rev1': rev1, 'rev2': rev2, 'main_obj': main_obj}

@login_required
def history_revert(request, content_type, object_id, revision, **kwargs):
    ctype = get_object_or_404(ContentType, model=content_type)
    main_obj = get_object_or_404(ctype.model_class(), pk=object_id)
    revision = int_or_404(revision)
    # we need to get a state of revision, which is previous to given
    if revision > 1:
        main_obj._revert_to_revision(revision-1)
    return HttpResponseRedirect(main_obj.get_absolute_url())
